package com.arpa.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.BatchRuleCache;
import com.arpa.wms.cache.GoodsCache;
import com.arpa.wms.cache.UnitCache;
import com.arpa.wms.common.util.OrderIdGeneratorUtil;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.dto.PutawayRegisterDTO;
import com.arpa.wms.domain.entity.*;
import com.arpa.wms.domain.enums.*;
import com.arpa.wms.domain.vo.PutawayRegisterVO;
import com.arpa.wms.mapper.PutawayRegisterMapper;
import com.arpa.wms.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static com.arpa.wms.domain.consts.NumConst.NUM_ZERO;

/**
 * <p>
 * 上架确认 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2020-08-04
 */
@Service
@Log4j2
public class PutawayRegisterServiceImpl extends ServiceImpl<PutawayRegisterMapper, PutawayRegister> implements IPutawayRegisterService {

    @Autowired
    private UnitCache unitCache;
    @Autowired
    private IPutawayItemService putawayItemService;
    @Autowired
    @Lazy
    private IWmsTaskService wmsTaskService;
    @Autowired
    @Lazy
    private IPutawayService putawayService;
    @Autowired
    private IWmsTaskItemService taskItemService;
    @Autowired
    private ILocationService locationService;

    @Autowired
    private PartyCache partyCache;
    @Autowired
    private GoodsCache goodsCache;
    @Autowired
    private BatchRuleCache batchRuleCache;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private IInventoryRecordService inventoryRecordService;

    private final static String PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY   = " putaway_quantity = putaway_quantity + ";

    /**
     * 保存
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public boolean save(PutawayRegister entity) {
        if(StringUtils.isBlank(entity.getCode())){
            entity.setCode(IdUtil.simpleUUID());
        }
        if(StringUtils.isBlank(entity.getCreatedBy())){
            entity.setCreatedBy(UserUtil.getCode());
            entity.setCreatedName(partyCache.translate(UserUtil.getCode()));
        }
        // 设置为有效数据，非删除
        entity.setDeleted(NUM_ZERO);

        return super.save(entity);
    }

    /**
     * 根据code更新实体
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public int updateByCode(PutawayRegister entity) {
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
        }
        return baseMapper.update(entity,new QueryWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getCode,entity.getCode()).eq(PutawayRegister::getGroupCode,UserUtil.getBranchCode()));
    }

    /**
     * 查询列表
     * @param putawayRegisterDTO
     * @return
     */
    @Override
    public List<PutawayRegisterVO> queryList(PutawayRegisterDTO putawayRegisterDTO){
        //排序字段名需要驼峰转数据库下划线类型字段名
        if(StringUtils.isNotEmpty(putawayRegisterDTO.getSortField())){
            putawayRegisterDTO.setSortField(CommonUtil.camel2Underline(putawayRegisterDTO.getSortField()));
        }
        List<PutawayRegisterVO> putawayRegisterVOList = baseMapper.queryList(putawayRegisterDTO);
        return putawayRegisterVOList;
    }

    /**
     * 查询合计,包含总数
     * @param putawayRegisterDTO
     * @return
     */
    @Override
    public PutawayRegisterVO queryListSum(PutawayRegisterDTO putawayRegisterDTO){
        PutawayRegisterVO putawayRegisterVO = baseMapper.queryListSum(putawayRegisterDTO);
        return putawayRegisterVO;
    }

    /**
     * PDA上架确认
     * @param putawayRegister
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inbound confirm(PutawayRegister putawayRegister) {
        String groupCode = UserUtil.getBranchCode();
        Inbound inbound = new Inbound();
        // 获取上架item，由于pda传过来的数据不全，需要使用它来填充部分数值
        PutawayItem item = putawayItemService.getOne(new QueryWrapper<PutawayItem>().lambda().eq(PutawayItem::getCode, putawayRegister.getPutawayItemCode()).eq(PutawayItem::getGroupCode,groupCode));
        if (item == null) {
            throw new ServiceException("上架明细不存在");
        }
        BigDecimal putawayQuantity = putawayRegister.getPutawayQuantity();
        BeanUtil.copyProperties(item, putawayRegister);
        putawayRegister.setPutawayQuantity(putawayQuantity);
        putawayRegister.setRemarks(StrUtil.EMPTY);
        putawayRegister.setOperatorBy(UserUtil.getCode());
        putawayRegister.setOperatorName(partyCache.translate(UserUtil.getCode()));

        WmsTask wmsTask = wmsTaskService.getOne(new QueryWrapper<WmsTask>().lambda().eq(WmsTask::getCode, putawayRegister.getTaskCode()).eq(WmsTask::getGroupCode,groupCode));
        // 自动占有任务
        if(ObjectUtil.isNotNull(wmsTask)) {
            wmsTaskService.autoAssign(wmsTask);
        }


        Putaway putaway = putawayService.getOne(new QueryWrapper<Putaway>().lambda().eq(Putaway::getCode, putawayRegister.getPutawayCode()).eq(Putaway::getGroupCode,groupCode));
        if (putaway == null) {
            throw new ServiceException("上架单【" + putawayRegister.getPutawayCode() + "】不存在");
        }

        // 校验上架库位
        Location location = locationService.getOne(new QueryWrapper<Location>().lambda()
                .eq(Location::getGroupCode,groupCode)
                .eq(Location::getWarehouseCode, putaway.getWarehouseCode())
                .eq(Location::getSerialNumber, putawayRegister.getLocation()));
        if (ObjectUtil.isNull(location)) {
            log.error("库位【{}】不存在，请确认", putawayRegister.getLocation());
            throw new ServiceException("库位：" + putawayRegister.getLocation() + "不存在，请确认");
        }
        if (!StrUtil.equalsAny(location.getStatus(), StatusEnum.ACTIVE.getValue())) {
            log.error("库位【{}】未启用，请先启用！", putawayRegister.getLocation());
            throw new ServiceException("库位：" + putawayRegister.getLocation() + "未启用，请先启用！");
        }

        putawayRegister.setLocation(location.getCode());
        putawayRegister.setSpaceCode(location.getSpaceCode());

        // 计算上架数量是否超过了计划数量，未超过，则更新一下上架明细
        BigDecimal itemPutawayQuantity = item.getPutawayQuantity().add(putawayRegister.getPutawayQuantity());
        if(itemPutawayQuantity.compareTo(item.getReceivedQuantity()) == 0) {
            item.setStatus(PutawayItemStatusEnum.FINISH.getValue());
            remove(new QueryWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getPutawayItemCode, putawayRegister.getPutawayItemCode()).eq(PutawayRegister::getStatus, PutawayItemStatusEnum.WAITING.getValue()).eq(PutawayRegister::getGroupCode,groupCode));
        } else if(itemPutawayQuantity.compareTo(item.getReceivedQuantity()) < 0){
            item.setStatus(PutawayItemStatusEnum.PUTAWAYING.getValue());
        } else {
            throw new ServiceException("上架数量超过了收货数量，请确认");
        }

        // XYTODO TODO 应该加锁或者在更新数量时判断是否超过了
        // 更新item上架数量、状态
        boolean updateItemFlag = putawayItemService.update(new UpdateWrapper<PutawayItem>().lambda()
                .eq(PutawayItem::getGroupCode,groupCode)
                .eq(PutawayItem::getCode, item.getCode()).apply(" received_quantity >= putaway_quantity + " + putawayRegister.getPutawayQuantity())
                .setSql(PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY + putawayRegister.getPutawayQuantity())
                .set(PutawayItem::getStatus, item.getStatus()));
        if(!updateItemFlag){
            throw new ServiceException("上架数量超过了收货数量，请确认");
        }

        // 更新库存

        // 根据上架单、上架明细、上架确认生成库存
        Inventory inventory = generateInventory(putaway, putawayRegister);

        // 查询是否有相同的库存
        Inventory sameInventory = inventoryService.hasSameInventory(inventory.getLot(), inventory.getGoodsCode(), inventory.getLocation(),
                inventory.getShipmentCode(), inventory.getGoodsStatus(), inventory.getIsLock(), inventory.getContainerBarCode(), inventory.getGmtStock());

        if (ObjectUtil.isNull(sameInventory)) {
            // 不存在相同库存则需要插入一条新库存信息
            inventoryService.save(inventory);
            sameInventory = inventory;
        } else {
            // 存在相同库存则只需调整库存
            inventoryService.adjustQuantity(sameInventory.getCode(), inventory.getQuantity());
        }

        // 记录库存变动日志
        Inventory tempInventory = inventoryService.getOne(new QueryWrapper<Inventory>().lambda().eq(Inventory::getCode, item.getTempInventoryCode()).eq(Inventory::getGroupCode,groupCode));
        inventoryRecordService.insertRecord(tempInventory, putaway.getCode(), inventory.getQuantity().negate(), InventoryRecordTypeEnum.INBOUND.getValue());
        inventoryRecordService.insertRecord(sameInventory, putaway.getCode(), inventory.getQuantity(), InventoryRecordTypeEnum.INBOUND.getValue());

        // 将临时库存中的数量减掉
        inventoryService.reduceQuantity(item.getTempInventoryCode(), inventory.getQuantity());

        // 保存当前未确认上架信息, 保存时，需要合并相同数据
        // 查询数据库中是否存在 已上架、 相同明细号（相同商品）、 相同库位的确认单
        PutawayRegister sameRegister = getOne(new QueryWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getStatus, PutawayItemStatusEnum.FINISH.getValue())
                .eq(PutawayRegister::getGroupCode,groupCode)
                .eq(PutawayRegister::getPutawayItemCode, item.getCode()).eq(PutawayRegister::getLocation, putawayRegister.getLocation()));
        if (ObjectUtil.isNotNull(sameRegister)) {
            update(new UpdateWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getCode, sameRegister.getCode())
                    .eq(PutawayRegister::getGroupCode,groupCode)
                    .setSql(PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY + putawayRegister.getPutawayQuantity())
                    .set(PutawayRegister::getStatus, PutawayItemStatusEnum.FINISH.getValue()));
        } else {
            putawayRegister.setCode(IdUtil.simpleUUID());
            putawayRegister.setSpaceCode(location.getSpaceCode());
            putawayRegister.setStatus(PutawayItemStatusEnum.FINISH.getValue());
            putawayRegister.setCreatedBy(UserUtil.getCode());
            putawayRegister.setDeleted(NUM_ZERO);
            // 更新上架确认明细中的批次、存货日期
            putawayRegister.setLot(inventory.getLot());
            putawayRegister.setGmtStock(inventory.getGmtStock());

            save(putawayRegister);
        }

        // 更新作业任务
        wmsTaskService.update(new UpdateWrapper<WmsTask>().lambda().eq(WmsTask::getCode, putawayRegister.getTaskCode())
                .eq(WmsTask::getGroupCode,groupCode)
                .setSql(" job_quantity = job_quantity + " + putawayRegister.getPutawayQuantity()));

        // 更新上架单上架数量 XYTODO TODO 应该与下面的再整合一下
        putawayService.update(new UpdateWrapper<Putaway>().lambda().eq(Putaway::getCode, item.getPutawayCode())
                .eq(Putaway::getGroupCode,groupCode)
                .setSql(PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY + putawayRegister.getPutawayQuantity())
        );


        // 根据上架确认单信息，更新收货模块多个单据上架信息
        putawayService.refreshReceivePutawayAndInboundQuantity(putawayRegister);

        int updateStatusIfFinishJob = wmsTaskService.updateStatusIfFinishJob(wmsTask.getCode(), WmsTaskJobStatusEnum.COMPLETED.getValue());
        if(updateStatusIfFinishJob >= NUM_ONE.intValue()) {
            List<PutawayItem> putawayItemList = putawayItemService.list(new QueryWrapper<PutawayItem>().lambda()
                    .eq(PutawayItem::getPutawayCode, item.getPutawayCode())
                    .eq(PutawayItem::getGroupCode,groupCode)
                    .in(PutawayItem::getStatus, PutawayItemStatusEnum.WAITING.getValue(), PutawayItemStatusEnum.PUTAWAYING.getValue()));
            if (IterUtil.isEmpty(putawayItemList)) {
               inbound = putawayService.check(putaway);

            } else {
                putawayService.update(new UpdateWrapper<Putaway>().lambda().eq(Putaway::getCode, item.getPutawayCode())
                        .eq(Putaway::getGroupCode, groupCode)
                        .set(Putaway::getStatus, PutawayStatusEnum.PUTAWAYING.getValue()));
            }
        } else {
            putawayService.update(new UpdateWrapper<Putaway>().lambda().eq(Putaway::getCode, item.getPutawayCode())
                    .eq(Putaway::getGroupCode, groupCode)
                    .set(Putaway::getStatus, PutawayStatusEnum.PUTAWAYING.getValue()));
        }


        return inbound;
    }

    /**
     * PDA托盘上架--重构
     * @param putawayRegister 由于托盘上架信息固定，所以putawayRegister只是承载关键数据，而非实际要上架的所有数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result palletConfirm(PutawayRegister putawayRegister) {
        String groupCode = UserUtil.getBranchCode();
        List<PutawayRegister> registers = new ArrayList<>();
        // 将任务分配给当前操作者
        WmsTask wmsTask = wmsTaskService.getOne(new QueryWrapper<WmsTask>().lambda().eq(WmsTask::getCode, putawayRegister.getTaskCode()).eq(WmsTask::getGroupCode,groupCode));
        if(ObjectUtil.isNotNull(wmsTask)) {
            wmsTaskService.autoAssign(wmsTask);
        }
        // 校验库位serialnumber，并赋值code
        Location location = locationService.getOne(new QueryWrapper<Location>().lambda()
                .eq(Location::getGroupCode,groupCode)
                .eq(Location::getWarehouseCode,wmsTask.getWarehouseCode())
                .eq(Location::getSerialNumber, putawayRegister.getLocation()));
        if (ObjectUtil.isNull(location)) {
            log.error("库位【{}】不存在", putawayRegister.getLocation());
            throw new ServiceException("库位：" + putawayRegister.getLocation() + "不存在，请确认");
        }
        if (!StrUtil.equalsAny(location.getStatus(), StatusEnum.ACTIVE.getValue())) {
            log.error("库位【{}】未启用，请先启用！", putawayRegister.getLocation());
            throw new ServiceException("库位：" + putawayRegister.getLocation() + "未启用，请先启用！");
        }

        // 校验上架单状态
        Putaway putaway = putawayService.getOne(new QueryWrapper<Putaway>().lambda().eq(Putaway::getCode, wmsTask.getSourceCode()).eq(Putaway::getGroupCode,groupCode));
        if (ObjectUtil.isNull(putaway)) {
            log.error("上架单【{}】不存在！", wmsTask.getSourceCode());
            throw new ServiceException("上架单！" + wmsTask.getSourceCode() + "不存在");
        }
        if (PutawayStatusEnum.FINISH_PUTAWAY.getValue().equals(putaway.getStatus())){
            log.error("上架单【{}】已完成，无法操作！", wmsTask.getSourceCode());
            throw new ServiceException("上架单已完成，无法操作！");
        }

        String putawayCode = putaway.getCode();
        // 获取任务明细
        List<WmsTaskItem> wmsTaskItems = taskItemService.list(new QueryWrapper<WmsTaskItem>().lambda().eq(WmsTaskItem::getTaskCode, wmsTask.getCode()).eq(WmsTaskItem::getGroupCode,groupCode));

        HashSet<String> uniqueRegisters = new HashSet<>();

        wmsTaskItems.stream().forEach(item -> {
            // 获取任务明细对应的上架明细
            PutawayItem putawayItem = putawayItemService.getOne(new QueryWrapper<PutawayItem>().lambda().eq(PutawayItem::getCode, item.getSourceCode()).eq(PutawayItem::getGroupCode,groupCode));

            // 根据上架明细生成一条上架register,将其作为模板，用于保存
            PutawayRegister register = new PutawayRegister();
            BeanUtil.copyProperties(putawayItem, register);
            register.setStatus(PutawayItemStatusEnum.WAITING.getValue());
            register.setPutawayItemCode(putawayItem.getCode());
            register.setRemarks(StrUtil.EMPTY);
            register.setStatus(PutawayItemStatusEnum.FINISH.getValue());
            register.setLocation(location.getCode());
            register.setSpaceCode(location.getSpaceCode());
            register.setCode(StrUtil.EMPTY);
            register.setCreatedBy(StrUtil.EMPTY);
            register.setPutawayQuantity(putawayItem.getReceivedQuantity());
            registers.add(register);

            // 根据上架单、上架明细、上架确认生成库存
            Inventory inventory = generateInventory(putaway, register);

            // 查询是否有相同的库存
            Inventory sameInventory = inventoryService.hasSameInventory(inventory.getLot(), inventory.getGoodsCode(), inventory.getLocation(),
                    inventory.getShipmentCode(), inventory.getGoodsStatus(), inventory.getIsLock(), inventory.getContainerBarCode(), inventory.getGmtStock());

            if (ObjectUtil.isNull(sameInventory)) {
                // 不存在相同库存则需要插入一条新库存信息
                inventoryService.save(inventory);
                sameInventory = inventory;
            } else {
                // 存在相同库存则只需调整库存
                inventoryService.adjustQuantity(sameInventory.getCode(), inventory.getQuantity());
            }

            // 记录库存变动日志
            Inventory tempInventory = inventoryService.getOne(new QueryWrapper<Inventory>().lambda().eq(Inventory::getCode, putawayItem.getTempInventoryCode()).eq(Inventory::getGroupCode,groupCode));
            inventoryRecordService.insertRecord(tempInventory, putaway.getCode(), inventory.getQuantity().negate(), InventoryRecordTypeEnum.INBOUND.getValue());
            inventoryRecordService.insertRecord(sameInventory, putaway.getCode(), inventory.getQuantity(), InventoryRecordTypeEnum.INBOUND.getValue());

            // 将临时库存中的数量减掉
            inventoryService.reduceQuantity(putawayItem.getTempInventoryCode(), inventory.getQuantity());

            // 保存当前未确认上架信息, 保存时，需要合并相同数据
            PutawayRegister savedRegister = getOne(new QueryWrapper<PutawayRegister>().lambda()
                    .eq(PutawayRegister::getStatus, PutawayItemStatusEnum.FINISH.getValue())
                    .eq(PutawayRegister::getPutawayItemCode, putawayItem.getCode()).eq(PutawayRegister::getLocation, register.getLocation()));
            if(savedRegister != null){
                update(new UpdateWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getCode, savedRegister.getCode())
                        .eq(PutawayRegister::getGroupCode,groupCode)
                        .setSql(PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY + register.getPutawayQuantity()));
            }else{
                savedRegister = register;
                save(savedRegister);
            }

            // 更新明细,如果收货数量> 之前上架数量+本次上架数量，则说明已经上架了一部分，不能上架
            boolean putawayFlag = putawayItemService.update(new UpdateWrapper<PutawayItem>().lambda().eq(PutawayItem::getCode, item.getSourceCode())
                    .eq(PutawayItem::getGroupCode,groupCode)
                    .apply(" received_quantity = putaway_quantity + " + savedRegister.getPutawayQuantity())
                    .set(PutawayItem::getPutawayQuantity, putawayItem.getReceivedQuantity())
                    .set(PutawayItem::getStatus, PutawayItemStatusEnum.FINISH.getValue()));
            if (!putawayFlag){
                throw new ServiceException("总上架数量已经超过收货数量，不能上架");
            }

            // 删除当前item下未确认的确认单, 为避免漏删，将未上架、上架中状态的都删除，避免有误用上架中状态的
            this.remove(new QueryWrapper<PutawayRegister>().lambda().eq(PutawayRegister::getPutawayItemCode, putawayItem.getCode())
                    .eq(PutawayRegister::getGroupCode,groupCode)
                    .in(PutawayRegister::getStatus, PutawayItemStatusEnum.WAITING.getValue(), PutawayItemStatusEnum.PUTAWAYING.getValue()));
            //status为上架的实际状态
            String status = getPutawayStatus(putawayCode,groupCode,register.getPutawayQuantity());
            // 更新上架单数量及状态
            putawayService.update(new UpdateWrapper<Putaway>().lambda().eq(Putaway::getCode, putaway.getCode())
                    .eq(Putaway::getGroupCode,groupCode)
                    .setSql(PUTAWAY_QUANTITY_EQUALS_PUTAWAY_QUANTITY + register.getPutawayQuantity())
                    .set(Putaway::getStatus,status)
            );

            // 根据上架确认单信息，更新收货模块多个单据上架信息
            if (!uniqueRegisters.contains(register.getPutawayItemCode())){
                // 根据上架确认单信息，更新收货模块多个单据上架信息
                putawayService.refreshReceivePutawayAndInboundQuantity(register);
                uniqueRegisters.add(register.getPutawayItemCode());
            }

            //上架完成则生成入库单
            boolean finishedPutaway = PutawayStatusEnum.FINISH_PUTAWAY.getValue().equals(status);
            if (finishedPutaway){
                putawayService.pdaCheck(putaway);
            }

            // 更新任务，托盘任务，所以一定是任务完成
            wmsTaskService.update(new UpdateWrapper<WmsTask>().lambda().eq(WmsTask::getCode, putawayRegister.getTaskCode())
                    .eq(WmsTask::getGroupCode,groupCode)
                    .setSql(" job_quantity = goods_quantity").set(WmsTask::getJobStatus, WmsTaskJobStatusEnum.COMPLETED.getValue()));

        });

        return Result.ok();
    }

    private String getPutawayStatus(String putawayCode,String groupCode,BigDecimal newPutawayQuantity) {
        Putaway putaway = putawayService.getOne(new LambdaQueryWrapper<Putaway>()
                .select(Putaway::getTotalQuantity,Putaway::getPutawayQuantity)
                .eq(Putaway::getCode, putawayCode)
                .eq(Putaway::getGroupCode, groupCode));
        //计算上架总数量
        BigDecimal putawayQuantity = putaway.getPutawayQuantity().add(newPutawayQuantity);
        return putaway.getTotalQuantity().compareTo(putawayQuantity) > 0 ? PutawayStatusEnum.PUTAWAYING.getValue() : PutawayStatusEnum.FINISH_PUTAWAY.getValue();
    }
    @Override
    public List<PutawayRegisterVO> queryListByCodes(List<String> codes) {
        return this.baseMapper.queryListByCodes(codes,UserUtil.getBranchCode());
    }

    private Inventory generateInventory(Putaway putaway, PutawayRegister register){
        Inventory inventory = new Inventory();
        BeanUtil.copyProperties(register, inventory);
        inventory.setCode(IdUtil.simpleUUID());
        inventory.setGroupCode(putaway.getGroupCode());
        inventory.setWarehouseCode(putaway.getWarehouseCode());
        inventory.setShipmentCode(putaway.getShipmentCode());
        inventory.setShipmentName(putaway.getShipmentName());
        inventory.setWarehouseSpaceCode(register.getSpaceCode());
        // 库存数量 = 上架数量*最小单位转换件装量
        inventory.setQuantity(register.getPutawayQuantity().multiply(register.getUnitConvertQuantity()));
        inventory.setIsLock(0);
        inventory.setDeleted(0);
        inventory.setGmtStock(register.getGmtStock());

        // 保存商品基本单位
        inventory.setGoodsUnit(register.getBasicUnit());
        inventory.setUnitName(register.getBasicUnitName());

        // 如果不是托盘，则库存上不会记录容器号
        if(!ContainerTypeEnum.PALLET.getValue().equals(register.getContainerType())){
            inventory.setContainerBarCode(StrUtil.EMPTY);
        }

        // 判断是否需要将收货批号打到库存上
        Map<String, Object> goodsMap = goodsCache.get(inventory.getGoodsCode());
        String lotNumber = goodsMap.getOrDefault("lotNumber", "").toString();
        Map<String, Object> batchRuleMap = batchRuleCache.get(lotNumber);
        if(batchRuleMap != null){
            String lotFlag = batchRuleMap.getOrDefault("lot", "0").toString();
            if(NUM_ONE.toString().equals(lotFlag)){
                inventory.setReceiveLot(register.getReceiveLot());
            } else {
                inventory.setReceiveLot(StrUtil.EMPTY);
            }
        }
        //收货登记明细里的有效期为1时，有两种情况形成的，一是确实为1，二是为空时设置的一个默认值
        if (register.getExpirationQuantity().compareTo(BigDecimal.ONE) == NumConst.NUM_ZERO) {
            //找到对应的商品
            Goods goods = goodsCache.getObj(register.getGoodsCode());
            inventory.setExpirationQuantity(goods.getQuality());
        } else {
            inventory.setExpirationQuantity(register.getExpirationQuantity());
        }
        // 生成库存批次
        String lot = OrderIdGeneratorUtil.generatorLot(inventory);
        inventory.setLot(lot);
        // 生成字段都包含的库存批次规则
        inventory.setFullLot(OrderIdGeneratorUtil.generatorFullLot(inventory));

        return inventory;
    }

    /**
     * 更新上架单的任务号
     * @param pValue
     * @param groupCode
     * @param taskCode
     * @return
     */
    @Override
    public boolean updateTaskCode(List<PutawayItem> pValue, String groupCode, String taskCode){
        List<String> putwayItemCodes = pValue.stream().map(PutawayItem::getCode).collect(Collectors.toList());
        return this.update(new LambdaUpdateWrapper<PutawayRegister>()
                .in(PutawayRegister::getPutawayItemCode, putwayItemCodes)
                .eq(PutawayRegister::getGroupCode, groupCode)
                .set(PutawayRegister::getTaskCode, taskCode));
    }

}
